//
//  PhotoDetail.swift
//  SwiftUILean
//
//  Created by wyknmjj on 2024/5/13.
//

import SwiftUI

struct PhotoDetail: View {
    @Environment(PhotoCoordinator.self) private var coordinator
    var body: some View {
        
        switch coordinator.result{
        case .error(let e):
            Text("Error \(e)")
        case .success(data: let list):
            //这里是把所有图片都展示出来的了
            VStack(spacing:0){
                NavigationBar()
                GeometryReader{
                    let size=$0.size
                    ScrollView(.horizontal) {
                        LazyHStack(spacing:0){
                            ForEach(list){item in
                                ImageView(item,size:size)
                            }
                        }
                        .scrollTargetLayout()
                    }
                    .scrollTargetBehavior(.paging)
                    .scrollIndicators(.hidden)
                    .scrollPosition(id: .init(get: {
                            return coordinator.detailScrollPosition
                        }, set: {
                            coordinator.detailScrollPosition=$0
                        }))
                    .onChange(of: coordinator.detailScrollPosition, { oldValue, newValue in
                        coordinator.didDetailPageChanged()
                    })
                    .background{
                            if let selectedItem = coordinator.selectedItem {
                                Rectangle()
                                    .fill(.clear)
                                    .anchorPreference(key: PhotoHeroKey.self, value: .bounds, transform: { anchor in
                                        return [selectedItem.id + "DEST" : anchor]
                                    })
                            }
                        }
                    .offset(coordinator.offset)
                    
                    Rectangle()
                        .foregroundStyle(.clear)
                        .frame(width: 10)
                        .contentShape(.rect)
                        .gesture(DragGesture(minimumDistance: 0)
                            .onChanged{ value in
                                let translation=value.translation
                                coordinator.offset=translation
                            
                                let heightProgress = max(min(translation.height / 200,1),0)
                                coordinator.dragProgress=heightProgress
                            }.onEnded{ value in
                                let translation=value.translation
                                let velocity=value.velocity
                                let height=translation.height + (velocity.height / 5)
                                
                                if height > (size.height + 0.5){
                                    coordinator.toggleView(show: false)
                                }else{
                                    withAnimation(.easeInOut(duration:0.2)){
                                        coordinator.offset = .zero
                                        coordinator.dragProgress = 0
                                    }
                                }
                            }
                        )
                }
                
                .opacity(coordinator.showDetailView ? 1 : 0)
                BottomIndicatorView(items: list)
                    .offset(y:coordinator.showDetailView ? (120 * coordinator.dragProgress) : 120)
                    .animation(.easeInOut(duration: 0.15), value: coordinator.showDetailView)
            }
            .onAppear{
                /**
                 这将确保详细视图加载并启动图层动画。
                 在主视图中点击该项目时不会切换它的原因是，有时可能无法加载目标视图。 在这种情况下，目标锚点将为 nil，并且图层不会被动画化。
                 
                即由于是FLIP,需要视图出现后才触发动画
                 */
                coordinator.toggleView(show: true)
            }
        }
    }
    @ViewBuilder
    func NavigationBar()-> some View{
        HStack{
            Button {
                coordinator.toggleView(show: false)
            } label: {
                HStack(spacing: 2){
                    Image(systemName: "chevron.left")
                        .font(.title3)
                    
                    Text("Back")
                }
            }
            
            
            Spacer(minLength: 0)
            Button{
                
            }label: {
                Image(systemName: "ellipsis")
                    .padding(10)
                    .background(.bar,in: .circle)
            }
        }
        .padding([.top,.horizontal],15)
        .padding(.bottom,10)
        .background(.ultraThinMaterial)
        .offset(y: coordinator.showDetailView ? (-120 * coordinator.dragProgress) : -120)
        .animation(.easeInOut(duration: 0.15),value: coordinator.showDetailView)
    }
    @ViewBuilder
    func ImageView(_ item:PhotoItem,size:CGSize)->some View{
        if let image=item.image{
            Image(uiImage: image)
                .resizable()
                .aspectRatio(contentMode: .fit)
                .frame(width: size.width,height: size.height)
                .clipped()
                .contentShape(.rect)
        }
    }
    
    
    
    @ViewBuilder
    func BottomIndicatorView(items:[PhotoItem])-> some View{
        GeometryReader{
            let size = $0.size
            
            ScrollView(.horizontal){
                LazyHStack(spacing:5){
                    ForEach(items){item in
                        if let image=item.previewImage{
                            Image(uiImage: image)
                                .resizable()
                                .aspectRatio(contentMode: .fill)
                                .frame(width: 50,height: 50)
                                .clipShape(.rect(cornerRadius: 10))
                                .scaleEffect(0.97)
                        }
                        
                    }
                }.padding(.vertical,10)
                 .scrollTargetLayout()
            }
            .safeAreaPadding(.horizontal,(size.width - 50) / 2)
            .overlay{
                RoundedRectangle(cornerRadius: 10)
                    .stroke(Color.primary, lineWidth: 2)
                    .frame(width: 50,height: 50)
                    .allowsHitTesting(true)
            }
            .scrollTargetBehavior(.viewAligned)
            .scrollPosition(id: .init(get: {return coordinator.detailIndicatorPosition}, set: {coordinator.detailIndicatorPosition=$0}))
            .scrollIndicators(.hidden)
            .onChange(of: coordinator.detailIndicatorPosition) { oldValue, newValue in
                coordinator.didDetailIndicatorPageChanged()
            }
        }.frame(height: 70)
            .background{
                Rectangle()
                    .fill(.ultraThinMaterial)
                    .ignoresSafeArea()
            }
    }
}

#Preview {
    PhotoAppView()
}
